<?php


namespace app\admin\pms\controller;

use app\admin\pms\logic\GoodsLogic;
use app\api\logic\GoodsSearchLogic;
use app\common\controller\BaseAdminController;
use app\model\pms\Goods;
use think\db\Query;

/**
 * 商品管理
 * Class GoodsController
 * @package app\admin\pms\controller
 */
class GoodsController extends BaseAdminController
{
    protected function init()
    {
        parent::init();
        $this->logic = new GoodsLogic();
    }

    protected function searchWhere()
    {
        $where = [
            ['is_del', '=', 0]
        ];
        $this->form['name'] && $where[] = ['name', 'like', "%{$this->form['name']}%"];
        $this->form['type'] && $where[] = ['type', '=', $this->form['type']];
        $this->form['cate_id'] && $where[] = ['cate_id', '=', $this->form['cate_id']];

        if ($this->form['tab_type'] == 'sales') {
            //销售中
            $where[] = ['is_show', '=', 1];
        }
        if ($this->form['tab_type'] == 'warehouse') {
            //仓库中
            $where[] = ['is_show', '=', 0];
        }
        if ($this->form['tab_type'] == 'early_warning') {
            //预警中
            $where[] = ['stock', '<=', 20];
        }
        if ($this->form['tab_type'] == 'recovery') {
            //回收站
            $where[] = ['is_del', '=', 1];
        }

        return $where;
    }

    public function list()
    {
        $query = $this->logic->search($this->searchWhere());
        $query->order($this->listOrder());
        if ($this->except) {
            $query->withoutField($this->field);
        } else {
            $query->field($this->field ?: '*');
        }
        $form = $this->form;
        $query->order($form->getSortField('id'), $form->getOrder("desc"));
        $query->with(array_merge([
            "brand" => function (Query $query) {
                $query->field(['id', 'name']);
            },
        ], Goods::getCateWith()));
        $data = $query->paginate([
            'page' => $form->getPage(),
            'list_rows' => $form->getPageSize(),
        ])->toArray();

        return $this->success($data);
    }

    public function add()
    {
        $goods_id = 0;
        $this->logic->transaction(function () use (&$goods_id) {
            $goods_id = $this->logic->addGoods(input());
        });
        GoodsSearchLogic::addGoodsChange([$goods_id]);
        return $this->success();
    }

    public function update()
    {
        $goods_id = 0;
        $this->logic->transaction(function () use (&$goods_id) {
            $goods_id = $this->logic->editGoods(input());
        });
        GoodsSearchLogic::addGoodsChange([$goods_id]);
        return $this->success();
    }

    public function read()
    {
        $data = [];
        if ($id = input('id')) {
            $data = $this->logic->readGoods(input('id'));
        }
        return $this->success($data);
    }
}